<template>
  <div>
    <el-input
      v-if="readonly"
      v-model="form.label"
      :disabled="disabled"
      :readonly="readonly"
      @click.native="getSelectTree"
      :placeholder="placeholder"
      :type="multiple ? 'textarea' : 'text'"
      :autosize="{ minRows: 1, maxRows: 4 }"
      prefix-icon="el-icon-search"
    >
    </el-input>
    <div v-else :style="multiple ? styleObject : {}">
      <el-input
        v-model="form.label"
        :readonly="readonly"
        :disabled="disabled"
        :placeholder="placeholder"
        :type="multiple ? 'textarea' : 'text'"
        :autosize="{ minRows: 1, maxRows: 4 }"
      >
        <el-button
          v-if="!multiple"
          slot="suffix"
          :disabled="disabled"
          @click="getSelectTree"
          icon="el-icon-search"
        ></el-button>
      </el-input>
      <span v-if="multiple && !disabled">
        <el-button
          :disabled="disabled"
          @click="getSelectTree"
          icon="el-icon-search"
        ></el-button>
      </span>
    </div>

    <el-dialog
      :title="openTitle"
      :visible.sync="selectOpen"
      width="800px"
      append-to-body
    >
      <el-form label-width="60px" @submit.native.prevent>
        <el-form-item label="关键字">
          <el-input v-model="searchDeviceName" />
        </el-form-item>
        <el-tree
          class="tree-border"
          :data="selectOptions"
          :default-checked-keys="selectChecked"
          v-loading="treeLoading"
          @check="handleDeptChecked"
          :default-expanded-keys="defaultExpandedKeys"
          :default-expand-all="false"
          show-checkbox
          ref="selectInfo"
          node-key="id"
          :filter-node-method="filterNode"
          @node-click="handleRowClick"
          empty-text="加载中，请稍后"
          :check-strictly="!this.multiple"
          style="height: 300px; overflow: auto"
        >
          <label slot-scope="{ data }">
            <i class="el-icon-s-opportunity" v-if="data.user"></i>
            <i class="el-icon-s-home" v-else></i>
            {{ data.label }}
          </label>
        </el-tree>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectScope">确 定</el-button>
        <el-button @click="selectOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataObj from './data'
// import { deviceTree as groupTreeData } from '@/api/device/dataView.js'
export default {
  name: 'el-input-dev-select',
  components: {},
  props: {
    value: {},
    id: {
      require: true,
      type: String
    },
    label: {
      require: false,
      type: String
    },
    type: {
      type: String,
      default: 'user'
    },
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      // 可选可读需传递 requireId=false
      type: Boolean,
      default: true
    },
    params: {
      // roleKey 角色 postIds 岗位 majorId 专业 deptId 部门
      type: Object,
      default: () => {
        return {}
      }
    },
    requireId: {
      type: Boolean,
      default: true
    },
    checks: {
      type: Array,
      default: () => {
        return null
      }
    },
    disabledIds: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      searchDeviceName: '',
      treeLoading: false,
      selectOpen: false,
      selectOptions: [],
      checkedNodes: [],
      selectChecked: [],
      isUser: null,
      openTitle: '',
      inputValue: null,
      form: {
        id: null,
        label: null,
        parentId: null,
        noCheck: null
      },
      queryParams: {},
      styleObject: {
        display: 'flex'
      }
    }
  },
  created () {
    this.rest()
    if (this.value) {
      this.initInput()
    }
  },
  computed: {
    valueComputed () {
      return {
        id: this.value[this.id],
        label: this.value[this.label]
      }
    },
    defaultExpandedKeys () {
      if (this.selectChecked.length === 0) {
        return this.selectOptions.map((e) => e.id)
      }
      return this.selectChecked
    }
  },
  watch: {
    searchDeviceName: function (val) {
      this.$refs.selectInfo.filter(val)
    },
    valueComputed: {
      handler (newValue, oldValue) {
        this.initInput()
      },
      deep: true
      // immediate: true
    },
    'form.label' (newValue, oldValue) {
      if (this.readonly) {
        this.selectOpen = false
        return
      }
      this.writeChange(newValue, oldValue)
    },
    form: {
      handler (val, oldVal) {
        this.selectOpen = false
        const newValue = val.id
        const oldValue = oldVal.id
        if ((newValue || null) === (oldValue || null)) {
          // 防止 undefined  null ''
          return
        }
        const temp = {}
        if (newValue) {
          temp[this.id] = newValue
          if (this.label) {
            temp[this.label] = val.label
          }
        } else {
          temp[this.id] = ''
          if (this.label) {
            temp[this.label] = ''
          }
        }
        let top = {} // 顶级节点
        if (temp[this.id] && this.selectOptions.length > 0) {
          top = this.selectOptions[0]
        }
        this.$emit('change', temp, oldVal, top, val, this.checkedNodes)
        if (this.value !== null && typeof this.value === 'object') {
          Object.assign(this.value, temp)
        } else {
          this.$emit('input', { ...this.inputValue, ...temp })
        }
      }
    }
  },
  methods: {
    rest () {
      this.form = {
        id: '',
        label: '',
        parentId: '',
        noCheck: ''
      }
    },
    writeChange (newValue, oldValue) {
      if ((newValue || null) === (oldValue || null)) {
        // 防止 undefined  null ''
        return
      }
      const temp = {}
      if (this.id) {
        temp[this.id] = this.selectOpen ? this.form.id : ''
      }
      temp[this.label] = newValue
      const oldTemp = { ...temp }
      oldTemp[this.label] = oldValue
      this.$emit('change', temp, oldTemp)
      if (this.value !== null && typeof this.value === 'object') {
        Object.assign(this.value, temp)
      } else {
        this.$emit('input', { ...this.inputValue, ...temp })
      }
      this.selectOpen = false
    },
    initInput () {
      this.inputValue = this.value
      this.form.id = this.inputValue[this.id]
      if (this.label) {
        this.form.label = this.inputValue[this.label]
      }
      if (this.requireId && !this.form.id) {
        this.form.label = ''
      }
    },
    getSelectTree () {
      if (this.disabled) return
      this.isUser = this.type === 'user'
      this.openTitle = this.isUser ? '选择设备' : '选择部门'
      this.selectOpen = true
      this.treeLoading = true
      this.queryParams = {
        ...{ noAuth: true, searchType: 3, params: { haveTag: this.isUser } },
        ...this.params
      }

      this.selectOptions = dataObj.data.data
      this.treeLoading = false
      this.selectChecked = []
      if (this.checks) {
        this.selectChecked = this.checks
      } else {
        if (this.form.id) {
          this.selectChecked = (this.form.id + '').split(',')
        }
      }

      // groupTreeData(this.queryParams).then((response) => {
      //   this.selectOptions = response.data
      //   this.treeLoading = false
      //   this.selectChecked = []
      //   if (this.checks) {
      //     this.selectChecked = this.checks
      //   } else {
      //     if (this.form.id) {
      //       this.selectChecked = (this.form.id + '').split(',')
      //     }
      //   }
      //   // this.$refs.selectInfo.setCheckedKeys(this.selectChecked)
      // })
    },
    // 点击行即可让复选框勾选
    handleRowClick (data, node) {
      if (this.disabledIds.findIndex((e) => e + '' === data.id) > -1) return
      // 类型相同勾选
      if (
        data.user === this.isUser &&
        (!data.children || data.children.length === 0)
      ) {
        this.handleDeptChecked(node)
      }
    },
    filterData (clickRow, data, checkedKeys) {
      if (data.checked) {
        // 勾选
        checkedKeys.push(clickRow.id)
        return checkedKeys
      } else {
        // 勾选取消
        const ids = [clickRow.id, clickRow.pId + '']
        return checkedKeys.filter((e) => !ids.includes(e))
      }
    },
    handleDeptChecked (data, nodes) {
      const clickRow = nodes === undefined ? data.data : data
      let checkedKeys = this.$refs.selectInfo.getCheckedKeys()
      console.log(checkedKeys)
      if (!this.multiple) {
        // 单选
        checkedKeys = []
      }
      data.checked = !data.checked
      if (nodes && nodes.checkedKeys) {
        // 点击复选框
        if (this.multiple && nodes.checkedKeys.length > 0) {
          checkedKeys = nodes.checkedKeys
        } else {
          checkedKeys = this.filterData(clickRow, data, checkedKeys)
        }
      } else {
        // 点击行
        checkedKeys = this.filterData(clickRow, data, checkedKeys)
      }
      this.$refs.selectInfo.setCheckedKeys(checkedKeys)
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    submitSelectScope () {
      const checkedNodes = this.$refs.selectInfo.getCheckedNodes()
      const filter = checkedNodes.filter((e) => e.noCheck)
      if (filter.length === 0) {
        this.checkedNodes = []
        this.rest()
        this.selectOpen = false
        return
      }
      this.checkedNodes = filter
      if (this.multiple) {
        let ids = []
        let labels = []
        if (filter.length > 0) {
          ids = filter.map((e) => e.id)
          labels = filter.map((e) => e.label)
        }
        this.form = {
          id: ids.join(','),
          label: labels.join('、'),
          noCheck: true
        }
      } else {
        if (!filter[0].noCheck) {
          this.$modal.msgError('不能选择【' + filter[0].label + '】节点！')
          return
        }
        this.checkedNodes = filter
        this.form = filter[0]
      }
    }
  }
}
</script>

<style scoped>
>>> .el-input__suffix {
  right: 0;
}
</style>
